package com.itheima.interceptors;

import com.itheima.utils.JwtUtils;
import com.itheima.utils.UserHolder;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Slf4j
@Component
public class DemoInterceptor implements HandlerInterceptor {
    @Override  //目标资源方法执行前执行 , 返回true : 放行 , 返回false: 不放行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        log.info("========DemoInterceptor使用的线程ID===============" + Thread.currentThread().getId());
//        UserHolder.setUserId(1);
//        return true;



        log.info("-----------DemoInterceptor进入资源之前-------------");
        String token = request.getHeader("token");

        if (token == null || "".equals(token)){
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;//拦截
        }
        try {
            Claims claims = JwtUtils.parseJWT(token);
            Integer id = claims.get("id" , Integer.class);
            UserHolder.setUserId(id);
            return true;
        } catch (Exception e) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
    }

    @Override  //目标资源方法执行后执行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        UserHolder.removeUserId();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        System.out.println("afterCompletion......");
    }

}
